package com.wj1c.push.wechat;

import com.alibaba.fastjson.JSON;
import com.wj1c.push.util.CommonUtil;
import com.wj1c.push.util.HttpClient;
import com.wj1c.push.util.SpringUtils;
import com.wj1c.push.wechat.request.AccessTokenRequest;
import com.wj1c.push.wechat.request.base.RequestMethod;
import com.wj1c.push.wechat.request.base.SupporRequest;
import com.wj1c.push.wechat.response.AccessTokenResponse;
import com.wj1c.push.wechat.response.base.Response;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * @author: Mr.Jiao
 * @date: 2018年09月03日
 */
public class WeChatRequest {

//    public static void main(String args[]) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
//        AccessTokenRequest request = new AccessTokenRequest();
////        request.setParams("wx3df24146968d3d43","db44a8bfa29027edeb430c197c3fe732");
//        AccessTokenResponse response = WeChatRequest.exec(request);
//        System.out.println(JSON.toJSONString(response));
//
//    }

    private static WeChatConfig config = null;

    static {
        config = SpringUtils.getBean(WeChatConfig.class);
    }

    public static<T extends Response> T exec(SupporRequest<T> request)  {
        assert config != null : "WeChatRequest.config can not load";
        request.setAppidAndSecret(config.getAppid(),config.getSecret());
        String method = null;
        if(request.getMethod() == RequestMethod.POST){
            method = "POST";
        }else{
            method = "GET";
        }
        String result = null;
        try {
            result = WeChatRequest.httpRequest(request.getRequestUrl(), method, request.getParams());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSON.parseObject(result, request.getResponseClass());
    }

    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) throws IOException {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod(requestMethod);
            if("GET".equalsIgnoreCase(requestMethod)){
                httpURLConnection.connect();
            }
            if(null != outputStr){
                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(outputStr.getBytes("utf-8"));
                outputStream.close();
            }
            InputStream inputStream = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while((str = bufferedReader.readLine())!= null){
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

}
